// pages/Itinerary/shareBanner/shareBanner.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    itineraryDetail: {},
    filePath: '',
    totalHeight: '',
    titleHeight: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    const itineraryDetail = JSON.parse(e.itineraryDetail)
    let totalHeight = 230;
    // 过滤 list_item 里的 child
    itineraryDetail.list_item = itineraryDetail.list_item.map(item => {
      return {
        ...item,
        child: item.child.filter(c => c.type == 11) // ✅ 只保留 type==11
      }
    })
    itineraryDetail.list_item.forEach(item => {
      totalHeight += 112;
      const extraChild = Math.max(0, item.child.length - 1);
      totalHeight += extraChild * 56;
    });
    let titleHeight = 0
    if (itineraryDetail.info.name && itineraryDetail.info.name.length > 13) {
      titleHeight += 30
    }
    console.log(totalHeight);
    this.setData({
      itineraryDetail,
      totalHeight: totalHeight + titleHeight,
      titleHeight
    })
    this.generatePoster()
  },
  roundRect(ctx, x, y, w, h, r) {
    ctx.beginPath()
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.quadraticCurveTo(x + w, y, x + w, y + r)
    ctx.lineTo(x + w, y + h - r)
    ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h)
    ctx.lineTo(x + r, y + h)
    ctx.quadraticCurveTo(x, y + h, x, y + h - r)
    ctx.lineTo(x, y + r)
    ctx.quadraticCurveTo(x, y, x + r, y)
    ctx.closePath()
  },
  async generatePoster() {
    wx.showLoading({
      title: '生成中...',
      mask: true
    })

    try {
      const {
        pixelRatio: dpr,
        screenWidth
      } = wx.getWindowInfo()

      const query = wx.createSelectorQuery()
      query.select('#posterCanvas')
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')

          this.canvas = canvas

          ctx.clearRect(0, 0, canvas.width, canvas.height)
          ctx.beginPath();

          const bg = canvas.createImage();
          bg.src = 'https://hkbus.tm0755.com/web/img/store-buttons/miniapp.jpg';
          bg.onload = () => {
            ctx.drawImage(bg, 212, 70 + titleHeight, 90, 90)
          }



          // 这里的宽高用 px
          const width = res[0].width
          const height = res[0].height

          canvas.width = width * dpr
          canvas.height = height * dpr
          ctx.scale(dpr, dpr)
          // 先定义圆角裁剪
          this.roundRect(ctx, 0, 0, width, height, 24)
          ctx.clip()

          ctx.fillStyle = '#fff'
          ctx.fillRect(0, 0, width, height)

          const titleHeight = this.data.titleHeight
          const gradientHeight = 230 + titleHeight
          const gradient = ctx.createLinearGradient(0, 0, 0, gradientHeight)
          gradient.addColorStop(0, '#CFEDE5')
          gradient.addColorStop(1, '#FFF')
          ctx.fillStyle = gradient
          ctx.fillRect(0, 0, width, gradientHeight)

          // 标题 40rpx → 20px
          ctx.fillStyle = '#000'
          ctx.font = 'bold 26px sans-serif'

          // 容器宽度 = canvas 宽度 - 左右边距（比如 48）
          const maxWidth = width - 48

          // 调用换行函数
          this.drawText(ctx, this.data.itineraryDetail.info.name, 24, 50, maxWidth, 34, 2)
          // 人均500💰香港精华景点一日游（国庆版）

          // const avatar = canvas.createImage();
          // avatar.src = '/pages/assets/image/avatar.jpg';
          // avatar.onload = () => {
          //   const size = 26; // 头像大小
          //   const x = 26; // 左上角X
          //   const y = 86 + titleHeight; // 左上角Y
          //   const radius = size / 2;

          //   // 裁剪圆形区域
          //   ctx.save(); // 保存当前状态
          //   ctx.beginPath();
          //   ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2, false);
          //   ctx.clip();

          //   // 绘制头像
          //   ctx.drawImage(avatar, x, y, size, size);

          //   ctx.restore(); // 恢复裁剪区域
          // };


          ctx.fillStyle = '#707070'
          ctx.font = 'bold 14px sans-serif'
          ctx.fillText(`${this.data.itineraryDetail.info.number_place}個行程`, 24, 100 + titleHeight)
          // 62
          ctx.fillStyle = '#707070'
          ctx.font = 'bold 14px sans-serif'
          ctx.fillText(`${this.data.itineraryDetail.info.number_day}天${this.data.itineraryDetail.info.number_day-1}晚`, 24, 130 + titleHeight)

          // ✅ 分隔虚线
          ctx.setLineDash([4, 3]) // 原来 8,6 → 打对折
          ctx.beginPath()
          ctx.moveTo(24, 180 + titleHeight)
          ctx.lineTo(width - 24, 180 + titleHeight)
          ctx.strokeStyle = '#ccc'
          ctx.stroke()
          ctx.setLineDash([])
          ctx.setLineDash([4, 3]) // 原来 8,6 → 打对折
          ctx.beginPath()
          ctx.moveTo(24, 175 + titleHeight)
          ctx.lineTo(width - 24, 175 + titleHeight)
          ctx.strokeStyle = '#ccc'
          ctx.stroke()
          ctx.setLineDash([])
          // 循环行程内容
          let y = 200 + titleHeight

          this.data.itineraryDetail.list_item.forEach(dayItem => {
            y += 24
            // DAY 标题 40rpx → 20px
            ctx.fillStyle = '#000'
            ctx.font = 'bold 20px sans-serif'
            ctx.fillText(`DAY ${dayItem.day_num}`, 24, y)
            y += 30

            dayItem.child.forEach(child => {

              // 景点标题 32rpx → 16px
              ctx.font = '16px sans-serif'
              ctx.fillStyle = '#000'
              ctx.fillText(child.title, 24, y)
              y += 24

              // 时间 24rpx → 12px
              ctx.font = '12px sans-serif'
              ctx.fillStyle = '#707070'
              ctx.fillText(`遊玩${child.minute}分钟`, 24, y)
              ctx.fillStyle = '#000'
              y += 30
            })
            y += 10
            // ✅ 分隔虚线
            ctx.setLineDash([4, 3]) // 原来 8,6 → 打对折
            ctx.beginPath()
            ctx.moveTo(24, y - 20)
            ctx.lineTo(width - 24, y - 20)
            ctx.strokeStyle = '#ccc'
            ctx.stroke()
            ctx.setLineDash([])


          })


          wx.canvasToTempFilePath({
            canvas,
            success: (res) => {
              this.setData({
                filePath: res.tempFilePath
              })

              console.log(res.tempFilePath);
            },
            fail: (err) => {
              console.error(err)
              wx.showToast({
                title: '生成失败',
                icon: 'none'
              })
            },
            complete: () => wx.hideLoading()
          })
        })
    } catch (err) {
      console.error(err)
      wx.hideLoading()
      wx.showToast({
        title: '生成失败',
        icon: 'none'
      })
    }
  },
  drawText(ctx, text, x, y, maxWidth, lineHeight, maxLines = 2) {
    let line = ''
    let lines = []
    for (let i = 0; i < text.length; i++) {
      const testLine = line + text[i]
      const {
        width
      } = ctx.measureText(testLine)

      if (width > maxWidth && line) {
        lines.push(line)
        line = text[i]
      } else {
        line = testLine
      }
    }
    if (line) lines.push(line)

    // 限制行数，超出显示省略号
    if (lines.length > maxLines) {
      lines = lines.slice(0, maxLines)
      const lastLine = lines[maxLines - 1]
      let truncated = lastLine
      while (ctx.measureText(truncated + '...').width > maxWidth) {
        truncated = truncated.slice(0, -1)
      }
      lines[maxLines - 1] = truncated + '...'
    }

    // 绘制
    lines.forEach((l, i) => {
      ctx.fillText(l, x, y + i * lineHeight)
    })
  },

  savePoster() {
    if (!this.canvas) {
      wx.showToast({
        title: '海报未生成',
        icon: 'none'
      })
      return
    }

    // 先转成本地文件路径
    wx.canvasToTempFilePath({
      canvas: this.canvas,
      success: (res) => {
        this.setData({
          filePath: res.tempFilePath
        }) // 存起来

        // 再保存到相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '已保存到相册'
            })
          },
          fail: (err) => {
            console.error('保存失败', err)
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      },
      fail: (err) => {
        console.error('导出失败', err)
        wx.showToast({
          title: '导出失败',
          icon: 'none'
        })
      }
    })
  }





})